package com.imesne.office.excel.write;

import com.imesne.office.excel.model.ExcelCell;
import com.imesne.office.excel.model.ExcelRow;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.Collection;

/**
 * Created by liyd on 17/7/5.
 */
public class ExcelRowWriterImpl extends AbstractConfigWriter implements ExcelRowWriter {

    public Row writeExcelTitleRow(Workbook workbook, Sheet sheet, ExcelRow excelRow) {
        Row row = this.getRow(sheet, excelRow);
        Collection<ExcelCell> excelCells = excelRow.getExcelCells();
        ExcelCellWriter excelCellWriter = this.getExcelWriterConfig().getExcelCellWriter();
        for (ExcelCell excelCell : excelCells) {
            excelCellWriter.writeExcelTitleCell(workbook, sheet, row, excelCell);
        }
        if (this.getExcelWriterConfig().getExcelWriteProcessor() != null) {
            this.getExcelWriterConfig().getExcelWriteProcessor().processTitleRow(excelRow, row, workbook, sheet);
        }
        return row;
    }

    public Row writeExcelRow(Workbook workbook, Sheet sheet, ExcelRow excelRow) {
        Row row = this.getRow(sheet, excelRow);
        Collection<ExcelCell> excelCells = excelRow.getExcelCells();
        ExcelCellWriter excelCellWriter = this.getExcelWriterConfig().getExcelCellWriter();
        for (ExcelCell excelCell : excelCells) {
            excelCellWriter.writeExcelCell(workbook, sheet, row, excelCell);
        }
        if (this.getExcelWriterConfig().getExcelWriteProcessor() != null) {
            this.getExcelWriterConfig().getExcelWriteProcessor().processRow(excelRow, row, workbook, sheet);
        }
        return row;
    }

    private Row getRow(Sheet sheet, ExcelRow excelRow) {
        ExcelWriterConfig excelWriterConfig = this.getExcelWriterConfig();
        Row row = null;
        Integer rowIndex = excelRow.getRowNum() - 1;
        if (excelWriterConfig.isAppend()) {
            row = sheet.getRow(rowIndex);
        }
        if (!excelWriterConfig.isAppend() || row == null) {
            row = sheet.createRow(rowIndex);
        }
        if (excelRow.getHeight() != null) {
            row.setHeightInPoints(excelRow.getHeight());
        }
        return row;
    }
}
